<template>
  <div id="sutdentList" class="magin-top">
    <div id="limit">
      学生姓名：
      <el-input class="magin-right" placeholder="请输入学生姓名关键字" v-model="name" clearable></el-input>
      学生学号：
      <el-input class="magin-right" placeholder="请输入学生学号" v-model="number" @keyup.native="number = checkInput(number)"
                clearable></el-input>
      性别：<el-select class="magin-right" v-model="gender" clearable placeholder="请选择性别">
            <el-option
              v-for="gender in genderOptions"
              :key="gender.value"
              :label="gender.label"
              :value="gender.value">
            </el-option>
          </el-select>
      <el-button type="primary" round @click="getStudents">查询</el-button>
      <el-button type="success" round @click="addStudentDialogVisible=true">新增</el-button>
    </div>
    <div id="table" class="magin-top">
      <el-table :data="studentList" style="width: 100%" >
        <el-table-column label="序号" type="index" ></el-table-column>
        <el-table-column label="姓名" prop="name" ></el-table-column>
        <el-table-column label="学号" prop="number"></el-table-column>
        <el-table-column label="班级" prop="grade" ></el-table-column>
        <el-table-column label="性别" prop="gender" >
          <template slot-scope="scope">
            <span v-if="scope.row.gender===0">男</span>
            <span v-else-if="scope.row.gender===1">女</span>
          </template>
        </el-table-column>
        <el-table-column label="宿舍" prop="dormitory" width="180">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="info" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div id="pagination">
      <el-row>
        <el-col :span="1" :offset="15">
          <el-pagination
            background
            :page-size="pageSize"
            :page-sizes="[5,10,15,20]"
            :current-page="pageNow"
            @size-change="handlePageSizeChange"
            @current-change="handlePageCurrentChange"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </el-col>
      </el-row>
    </div>
    <div id="addStudentDialog">
      <add-student-dialog :add-student-dialog-visible="addStudentDialogVisible"></add-student-dialog>
    </div>
    <div id="updateStudentDialog">
      <el-dialog title="编辑" :visible.sync="updateStudentDialogVisible" :close-on-click-modal="false" :before-close="closeDialog" width="500px">
        <div id="studentDetail">
          <el-form label-position="left" :model="studentDetail" ref="studentDetail" label-width="80px" :rules="rules">
            <el-form-item label="学生姓名" prop="name">
              <el-input v-model="studentDetail.name" style="width: 300px;"></el-input>
            </el-form-item>
            <el-form-item label="学生学号" prop="number">
              <el-input v-model="studentDetail.number" style="width: 300px;"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-select v-model="studentDetail.gender" placeholder="请选择性别" @change="getDormitory">
                <el-option
                  v-for="item in genderOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="班级" prop="grade">
              <el-cascader
                v-model="studentDetail.grade"
                placeholder="请选择班级"
                :options="gradeOptions"
                :props="{expandTrigger: 'hover',label:'name',value:'id'}">
              </el-cascader>
            </el-form-item>
            <el-form-item label="宿舍" prop="dormitory">
              <el-cascader
                v-model="studentDetail.dormitory"
                placeholder="请选择宿舍"
                :options="dormotoryOptions"
                :props="{ expandTrigger: 'hover',label:'name',value:'id' }">
              </el-cascader>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="updateStudent">保存</el-button>
              <el-button type="info" @click="closeDialog">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </div>
  </div>

</template>

<script>
  import student from '@/api/student/student'
  import dormitory from '@/api/dormitory/dormitory'
  import grade from '@/api/grade/grade'
import AddStudentDialog from './AddStudentDialog.vue'
  export default {
  components: { AddStudentDialog },
    name: 'LeaveList',
    data() {
      return {
        name: '',
        number: '',
        gender: '',
        pageNow: 1,
        pageSize: 5,
        total: 0,
        addStudentDialogVisible:false,
        updateStudentDialogVisible:false,
        rules: {
          name: [
            { required: true, message: '请输入学生姓名', trigger: 'blur' },
            { min: 2, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          number: [
            { required: true, message: '请输入学生学号', trigger: 'change' }
          ],
          gender: [
            { required: true, message: '请选择性别', trigger: 'change' }
          ],
          grade: [
            { required: true, message: '请选择班级', trigger: 'change' }
          ],
          dormitory: [
            { required: true, message: '请选择宿舍', trigger: 'change' }
          ]
        },
        genderOptions: [
          {
            label: '男孩',
            value: 0
          },
          {
            label: '女孩',
            value: 1
          }
        ],
        gradeOptions: [],
        dormotoryOptions:[],
        studentList: [],
        studentDetail:{
          id:0,
          name:'',
          number:'',
          gender:1,
          grade:[],
          dormitory:[]
        }
      }
    },
    created() {
      this.getStudents()
    },
    mounted() {
      grade.getGradeAndClazz().then(res=>{
        this.gradeOptions = res.data
      })
    },
    methods: {

      /*检验数字*/
      checkInput(num) {
        var str = num
        var len1 = str.substr(0, 1)
        var len2 = str.substr(1, 1)
        //如果第一位是0，第二位不是点，就用数字把点替换掉
        if (str.length > 1 && len1 === 0 && len2 !== '.') {
          str = str.substr(1, 1)
        }
        //第一位不能是.
        if (len1 === '0') {
          str = ''
        }
        //限制只能输入一个小数点
        if (str.indexOf('.') !== -1) {
          str = ''
        }
        //正则替换
        str = str.replace(/[^\d^.]+/g, '') // 保留数字和小数点
        str = str.replace(/\.\d\d\d$/, '') // 小数点后只能输两位
        return str
      },
      /*获取学生信息*/
      getStudents() {
        var studentPageParams = {
          pageNow: this.pageNow,
          pageSize: this.pageSize
        }
        if (this.gender === 0 || this.gender === 1) {
          this.$set(studentPageParams, 'gender', this.gender)
        }
        if (this.number.length > 0) {
          this.$set(studentPageParams, 'number', this.number)
        }
        if (this.name.length > 0) {
          this.$set(studentPageParams, 'name', this.name)
        }
        student.getStudents(studentPageParams).then(res => {
          this.total = res.total
          this.studentList = res.data
        }).catch(erro => {
          console.log(erro)
        })
      },
      /*改变页面大小*/
      handlePageSizeChange(pageSize) {
        this.pageSize = pageSize
        this.getStudents()
      },
      /*改变当前页*/
      handlePageCurrentChange(pageNow) {
        this.pageNow = pageNow
        this.getStudents()
      },
      /**
       * 执行编辑操作*
       * @param row
       */
      handleEdit(row) {
        this.getDormitory(row.gender)
        this.studentDetail.id = row.id
        this.studentDetail.name = row.name
        this.studentDetail.gender = row.gender
        this.studentDetail.number = row.number
        this.studentDetail.grade[0]=row.gradeId
        this.studentDetail.grade[1]=row.clazzId
        this.studentDetail.dormitory[0] = row.buildingId
        this.studentDetail.dormitory[1] = row.dormitoryId
        this.updateStudentDialogVisible = true
      },
      /*查询寝室信息*/
      getDormitory(genderId){
        dormitory.getDormitoryByGender(genderId).then(res=>{
          this.dormotoryOptions = res.data
        })
      },
      /*修改信息*/
      updateStudent(){
        var studentInfo = {
          id:this.studentDetail.id,
          name:this.studentDetail.name,
          number:this.studentDetail.number,
          gender:this.studentDetail.gender,
          gradeId: this.studentDetail.grade[0],
          clazzId:this.studentDetail.grade[1],
          buildingId:this.studentDetail.dormitory[0],
          dormitoryId:this.studentDetail.dormitory[1]
        }
        student.updStudent(studentInfo).then(()=>{
          this.$message.success("修改成功")
          this.getStudents()
          this.$refs['studentDetail'].resetFields()
          this.closeDialog()
        })
      },
      /**
       * 执行删除操作
       * @param id   行对象
       */
      handleDelete(id) {
        this.$confirm('确认删除该学生？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          student.delStudentById(id)
            .then(()=>{
              this.getStudents()
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            })
        })
      },
      /*关闭dialog*/
      closeDialog(){
        this.addStudentDialogVisible = false
        this.updateStudentDialogVisible = false
      }
    }
  }
</script>

<style scoped>
  .magin-right {
    margin-right: 20px;
    width: 200px;
  }

  .magin-top {
    margin-top: 20px;
  }

  #table {
    margin-left: 20px;
  }
</style>
